package org.xxpay.mch.user.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.MchAccount;
import org.xxpay.core.entity.MchAccountHistory;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.PayProduct;
import org.xxpay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author: dingzhiwei
 * @date: 17/12/6
 * @description:
 */
@RestController
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/account")
@PreAuthorize("hasRole('"+ MchConstant.MCH_ROLE_NORMAL+"')")
public class AccountController extends BaseController {

    /**
     * 查询账户信息
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get() {
        MchAccount mchAccount = commonService.mchAccountService.findByMchId(getUser().getId());
        JSONObject object = (JSONObject) JSON.toJSON(mchAccount);
        object.put("availableBalance", mchAccount.getAvailableBalance());                       // 可用余额
        object.put("availableSettAmount", mchAccount.getAvailableSettAmount());                 // 可结算金额
        object.put("availableAgentpayBalance", mchAccount.getAvailableAgentpayBalance());       // 可用代付余额

        //商户代付出款账户类型
        object.put(MchConstant.AGENTPAY_OUT_ACCOUNT_CONFIG_KEY,
                commonService.sysConfigService.getValByCode(MchConstant.AGENTPAY_OUT_ACCOUNT_CONFIG_KEY));

        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 查询资金流水列表
     * @return
     */
    @RequestMapping("/history_list")
    @ResponseBody
    public ResponseEntity<?> historyList(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        MchAccountHistory mchAccountHistory = getObject(param, MchAccountHistory.class);
        int count = commonService.mchAccountHistoryService.count(getUser().getId(), mchAccountHistory, getQueryObj(param));
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<MchAccountHistory> mchAccountHistoryList = commonService.mchAccountHistoryService
                .select(getUser().getId(), (getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), mchAccountHistory, getQueryObj(param));
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mchAccountHistoryList, count));
    }

    /**
     * 查询资金流水列表
     * @return
     */
    @RequestMapping("/history_get")
    @ResponseBody
    public ResponseEntity<?> historyGet(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        MchAccountHistory mchAccountHistory = commonService.mchAccountHistoryService
                .findById(getUser().getId(), id);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(mchAccountHistory));
    }

    @RequestMapping("/exportExcel")
    @ResponseBody
    public String exportExcel(HttpServletRequest request) throws Exception {

        JSONObject param = getJsonParam(request);
        MchAccountHistory mchAccountHistory = getObject(param, MchAccountHistory.class);
        int count = commonService.mchAccountHistoryService.count(getUser().getId(), mchAccountHistory, getQueryObj(param));

        if(count > MchConstant.MAX_EXPORT_ROW) return RetEnum.RET_SERVICE_OUT_OF_RANGE_MAX_EXPORT_ROW.getMessage();

        List<MchAccountHistory> mchAccountHistoryList = commonService.mchAccountHistoryService
                .select(getUser().getId(), 0, MchConstant.MAX_EXPORT_ROW, mchAccountHistory, getQueryObj(param));

        List<List> excelData = new ArrayList<>();
        List header = Arrays.asList(new String[]{"记录ID", "变更前余额(元)", "变更金额(元)", "变更后余额(元)", "业务类型", "业务订单", "订单金额(元)", "手续费(元)", "时间"});
        excelData.add(header);
        for(MchAccountHistory record : mchAccountHistoryList){
            List rowData = new ArrayList<>();
            rowData.add(record.getId());
            rowData.add(AmountUtil.convertCent2Dollar(record.getBalance()+""));

            String prefix = record.getFundDirection() == MchConstant.FUND_DIRECTION_ADD ? "+" : "-";
            rowData.add(prefix + AmountUtil.convertCent2Dollar(record.getAmount()+""));

            rowData.add(AmountUtil.convertCent2Dollar(record.getAfterBalance()+""));
            rowData.add(MchConstant.convertBizType(record.getBizType(), MchConstant.SYSTYPE_MCH));
            rowData.add(record.getOrderId());
            rowData.add(record.getOrderAmount() != null ? AmountUtil.convertCent2Dollar(record.getOrderAmount()+"") : "");
            rowData.add(record.getFee() != null ? AmountUtil.convertCent2Dollar(record.getFee() + "") : "");
            rowData.add(DateUtil.date2Str(record.getCreateTime()));
            excelData.add(rowData);
        }

        super.writeExcelStream("资金流水", excelData);
        return null;
    }


}
